package com.xgkj.diyiketang.fragment;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.CreateQuestionActivity;
import com.xgkj.diyiketang.activity.UpdateNickNameActivity;
import com.xgkj.diyiketang.activity.UpdateSigature;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.UpdateIconTask;
import com.xgkj.diyiketang.task.UploadImage;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.GetImagePathUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;

import net.bither.util.NativeUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment_Xuanze extends BaseFragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    private NextOnClickListener mListener;
    private View view;
    private RelativeLayout titleLayout;
    private TextView back;
    private ClearableEditText tiankongEdit;
    private RadioGroup xuanzeRadiogroup;
    private RadioButton daanA;
    private RadioButton daanB;
    private RadioButton daanC;
    private RadioButton daanD;
    private ImageView questionImage;
    private ImageView answerImage;
    private TextView titleText;
    private View xuanzeLine;
    private String mType;
    private CreateQuestionActivity mActivity;
    private Context mContext;


    private PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 0;
    private static final int CHOOSE_REQUEST = 11;
    private static final int CROP_REQUEST = 2;
    private File questionFile;
    private File answerFile;
    private File testFile;
    private String local_url;
    private static final String CAMERA_FILE = "diyiketang/img";
    InputMethodManager im;
    private String rightAnswer;
    private String questionUrl;
    private String answerUrl;
    private int chooseType;//1问题 2答案
    private int uploadTaskId = -1;
    private ProgressDialog mProgressDialog;

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_fragment_xuanze, null);
        }

        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        mContext = getActivity();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = (CreateQuestionActivity) getActivity();
        if (mActivity != null) {
            mType = mActivity.questionType;
        }
        titleLayout = (RelativeLayout) view.findViewById(R.id.title_layout);
        titleText = (TextView) view.findViewById(R.id.title);

        back = (TextView) view.findViewById(R.id.back);
        back.setOnClickListener(this);
        view.findViewById(R.id.ok_btn).setOnClickListener(this);
        tiankongEdit = (ClearableEditText) view.findViewById(R.id.tiankongEdit);
        xuanzeRadiogroup = (RadioGroup) view.findViewById(R.id.xuanze_radiogroup);
        xuanzeRadiogroup.setOnCheckedChangeListener(this);
        daanA = (RadioButton) view.findViewById(R.id.daan_a);
        daanB = (RadioButton) view.findViewById(R.id.daan_b);
        daanC = (RadioButton) view.findViewById(R.id.daan_c);
        daanD = (RadioButton) view.findViewById(R.id.daan_d);
        questionImage = (ImageView) view.findViewById(R.id.question_image);
        answerImage = (ImageView) view.findViewById(R.id.answer_image);
        questionImage.setOnClickListener(this);
        answerImage.setOnClickListener(this);
        xuanzeLine = view.findViewById(R.id.xuanze_line);
        if (mType != null && mType.equals("0")) {
            titleText.setText(R.string.tiankongti);
            xuanzeRadiogroup.setVisibility(View.GONE);
            xuanzeLine.setVisibility(View.GONE);
            tiankongEdit.setVisibility(View.VISIBLE);
        } else if (mType != null && mType.equals("1")) {
            titleText.setText(R.string.xuanzeti);
            xuanzeRadiogroup.setVisibility(View.VISIBLE);
            xuanzeLine.setVisibility(View.VISIBLE);
            tiankongEdit.setVisibility(View.GONE);
        }

        File folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        String fileName = "question" + System.currentTimeMillis() + ".jpeg";
        String file1Name = "answer" + System.currentTimeMillis() + ".jpeg";
//        String file2Name = "test" + System.currentTimeMillis() + ".jpg";
        questionFile = new File(folder, fileName);
        answerFile = new File(folder, file1Name);
//        testFile = new File(folder, file2Name);
        im = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        initPopWindow();
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ok_btn:
                if (tiankongEdit.getVisibility() == View.VISIBLE) {
                    rightAnswer = tiankongEdit.getText().toString();
                }
                if (mListener != null) {
                    mListener.onNextClick();
                }
                try {
                    im.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.back:
                if (mListener != null) {
                    mListener.onBackClick();
                }
                break;
            case R.id.question_image:
                chooseType = 1;

                try {
                    im.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                popWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.answer_image:
                chooseType = 2;
                try {
                    im.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                popWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.person_signature_layout:
                Intent signature_intent = new Intent(mContext, UpdateSigature.class);
                startActivity(signature_intent);
                break;
            case R.id.takephoto:
                popWindow.dismiss();
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (chooseType == 1) {
                    camera_intent
                            .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(questionFile));
                } else if (chooseType == 2) {
                    camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(answerFile));
                }
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
//                Intent intent = new Intent(mContext, PhoneMainActivity.class);
//                startActivityForResult(intent,300);
                Intent choose_intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    choose_intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    choose_intent.setAction(Intent.ACTION_GET_CONTENT);
                }
                choose_intent.setType("image/*");
                startActivityForResult(choose_intent, CHOOSE_REQUEST);
                break;
            case R.id.cancle:
                popWindow.dismiss();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                File file = null;
                if (chooseType == 1) {
                    file = questionFile;
                } else if (chooseType == 2) {
                    file = answerFile;
                }
                if (file == null || !file.exists()) {
                    return;
                }
//                PalLog.e("文件大小:", file.length() + "");

                /*Bitmap bitmap = null;
                OutputStream outputStream = null;
                try {
                    bitmap = revitionImageSize(file.getAbsolutePath());
                    outputStream = new FileOutputStream(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null && outputStream != null) {
                    BufferedOutputStream out = null;
                    out = new BufferedOutputStream(outputStream);
                    boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG,
                            60, out);
                    bitmap.recycle();
                    uploadImage(file.getAbsolutePath());
                }*/
                Uri uri = Uri.fromFile(file);
                startPhotoZoom(uri);
//                uploadImage(mFile.getAbsolutePath());
                break;

            case CHOOSE_REQUEST:
                if (resultCode != Activity.RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;

                Uri choose_uri = data.getData();
               /* File choosefile = null;
                if (chooseType == 1){
                    choosefile = questionFile;
                }else if (chooseType == 2){
                    choosefile = answerFile;
                }


                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                    local_url = GetImagePathUtil.getPath(mContext, choose_uri);
                }

                Bitmap choosebitmap = null;
                OutputStream chooseoutputStream = null;
                try {
                    choosebitmap = revitionImageSize(local_url);
                    chooseoutputStream = new FileOutputStream(choosefile);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (choosebitmap != null && chooseoutputStream != null) {
                    BufferedOutputStream out = null;
                    out = new BufferedOutputStream(chooseoutputStream);
                    boolean isSuccess = choosebitmap.compress(Bitmap.CompressFormat.JPEG,
                            60, out);
                    choosebitmap.recycle();
                    uploadImage(choosefile.getAbsolutePath());
                }*/

                startPhotoZoom(choose_uri);
                break;

            case CROP_REQUEST:
                if (resultCode != Activity.RESULT_OK) {
                    return;
                }
                if (data == null)
                    return;
                Bitmap bitmap = null;// = (Bitmap) data.getExtras().get("data");
                OutputStream outputStream = null;
                if (chooseType == 1) {
                    try {
                        bitmap = revitionImageSize(questionFile.getAbsolutePath());
                        outputStream = new FileOutputStream(questionFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (chooseType == 2) {
                    try {
                        bitmap = revitionImageSize(answerFile.getAbsolutePath());
                        outputStream = new FileOutputStream(answerFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (bitmap != null && outputStream != null) {
                    BufferedOutputStream out = null;
                    out = new BufferedOutputStream(outputStream);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
                    int moptions = 100;
                    bitmap.compress(Bitmap.CompressFormat.JPEG, moptions, baos);
                    // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                    while (baos.toByteArray().length / 1024 > 300) {
                        // 重置baos即清空baos
                        baos.reset();
                        // 每次都减少10
                        moptions -= 10;
                        // 这里压缩options%，把压缩后的数据存放到baos中
                        bitmap.compress(Bitmap.CompressFormat.JPEG, moptions, baos);
                    }

                    boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG,
                            moptions, out);
                    if (bitmap != null && !bitmap.isRecycled()) {
                        bitmap.recycle();
                        bitmap = null;
                    }

                    if (chooseType == 1) {
                        uploadImage(questionFile.getAbsolutePath());
                    } else if (chooseType == 2) {
                        uploadImage(answerFile.getAbsolutePath());
                    }
                }

                break;
            default:
                break;
        }
    }

    public Bitmap revitionImageSize(String path) throws IOException {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                new File(path)));
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
//        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        BitmapFactory.decodeStream(in, null, options);
        int bitmapWidth = options.outWidth;
        int bitmapHeight = options.outHeight;
        int screenWidth = ViewUtil.getScreenWidth(mContext);
        int screenHeight = ViewUtil.getScreenHeight(mContext);
        int inWidthSampleSize = bitmapWidth / screenWidth;
        int inHeightSampleSize = bitmapHeight / screenHeight;
        int inSampleSize = 1;
        if (inWidthSampleSize > inHeightSampleSize) {
            inSampleSize = inHeightSampleSize;
        } else {
            inSampleSize = inWidthSampleSize;
        }
        if (inSampleSize < 1) {
            inSampleSize = 1;
        }

        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
        in = new BufferedInputStream(new FileInputStream(
                new File(path)));
        Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
        in.close();

//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
//        // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
//        int moptions = 80;
//        bitmap.compress(Bitmap.CompressFormat.JPEG, moptions, baos);
//        // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
//        while (baos.toByteArray().length / 1024 > 300) {
//            // 重置baos即清空baos
//            baos.reset();
//            // 每次都减少10
//            moptions -= 10;
//            // 这里压缩options%，把压缩后的数据存放到baos中
//            bitmap.compress(Bitmap.CompressFormat.JPEG, moptions, baos);
//        }

//        NativeUtil.saveBitmap(bitmap,moptions,path,true);
////        NativeUtil.saveBitmap(bitmap,moptions,testFile.getAbsolutePath(),false);
//        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(answerFile));
//        bitmap.compress(Bitmap.CompressFormat.JPEG,moptions,outputStream);
//        if (bitmap != null && !bitmap.isRecycled()) {
//            bitmap.recycle();
//            bitmap = null;
//        }

        return bitmap;
    }


    private void uploadImage(String path) {
        showProgressDialog();
        UploadImage task = new UploadImage(path);
        task.addListener(new MyTaskEventListener(mContext));
        uploadTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = DialogUtil.showProgressDialog(mContext, mContext.getString(R.string.get_pageinfo_loading), null);
        }
        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            local_url = GetImagePathUtil.getPath(mContext, uri);
            if (local_url != null) {
                uri = Uri.fromFile(new File(local_url));
            }
        }
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", 360);
//        intent.putExtra("outputY", 360);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", false);
        if (chooseType == 1) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(questionFile));
        } else if (chooseType == 2) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(answerFile));
        }
        startActivityForResult(intent, CROP_REQUEST);
    }

    private int mCheckId;

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (mCheckId == checkedId) return;
        mCheckId = checkedId;
        switch (checkedId) {
            case R.id.daan_a:
                rightAnswer = "A";
                break;

            case R.id.daan_b:
                rightAnswer = "B";
                break;

            case R.id.daan_c:
                rightAnswer = "D";
                break;

            case R.id.daan_d:
                rightAnswer = "D";
                break;
        }
    }

    class MyTaskEventListener extends ShowToastTaskEventListener {

        public MyTaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            hideProgressDialog();
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == uploadTaskId) {
                if (chooseType == 1) {
                    if (data != null) {
                        JSONObject jsonObject = (JSONObject) data;
                        questionUrl = jsonObject.getString("imageId");
                        String path = jsonObject.getString("imageURL");
                        ImageCache.getInstance(mContext).loadBitmapToView(questionImage, path, null);
                    }

                    if (questionFile.exists()) {
//                        questionFile.delete();
                    }
                } else if (chooseType == 2) {
                    if (data != null) {
                        JSONObject jsonObject = (JSONObject) data;
                        answerUrl = jsonObject.getString("imageId");
                        String path = jsonObject.getString("imageURL");
                        ImageCache.getInstance(mContext).loadBitmapToView(answerImage, path, null);
                    }
                    if (answerFile.exists()) {
//                        answerFile.delete();
                    }
                }
                hideProgressDialog();
            }
        }
    }

    public String getAnswerUrl() {
        return answerUrl;
    }

    public String getRightAnswer() {
        return rightAnswer;
    }

    public String getQuestionUrl() {
        return questionUrl;
    }

    public interface NextOnClickListener {
        public void onNextClick();

        public void onBackClick();
    }

    public void setNextOnclickListener(NextOnClickListener listener) {
        mListener = listener;
    }

}
